// 获取菜品数据
const { dishes, categories } = require('../../data/dishes');

Page({
  data: {
    dishes: [],
    categories: [],
    currentCategory: '全部',
    searchQuery: '',
    sortBy: 'default',
    filteredDishes: []
  },
  
  onLoad: function () {
    this.setData({
      dishes,
      categories,
      filteredDishes: dishes
    });
    
    this.filterDishes();
  },
  
  // 切换分类
  switchCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category
    });
    
    this.filterDishes();
  },
  
  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchQuery: e.detail.value
    });
    
    this.filterDishes();
  },
  
  // 清空搜索
  clearSearch: function() {
    this.setData({
      searchQuery: ''
    });
    
    this.filterDishes();
  },
  
  // 设置排序方式
  setSortBy: function(e) {
    const sortBy = e.currentTarget.dataset.sort;
    this.setData({
      sortBy
    });
    
    this.filterDishes();
  },
  
  // 过滤菜品
  filterDishes: function() {
    let filtered = [...this.data.dishes];
    const { currentCategory, searchQuery, sortBy } = this.data;
    
    // 按分类过滤
    if (currentCategory !== '全部') {
      filtered = filtered.filter(dish => dish.category === currentCategory);
    }
    
    // 按搜索词过滤
    if (searchQuery) {
      filtered = filtered.filter(dish => 
        dish.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        dish.description.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }
    
    // 排序
    switch (sortBy) {
      case 'price-asc':
        filtered.sort((a, b) => a.price - b.price);
        break;
      case 'price-desc':
        filtered.sort((a, b) => b.price - a.price);
        break;
      case 'popularity':
        filtered.sort((a, b) => b.likes - a.likes);
        break;
      default:
        // 默认排序，保持原顺序
        break;
    }
    
    this.setData({
      filteredDishes: filtered
    });
  },
  
  // 点击菜品
  onDishClick: function(e) {
    const dish = e.detail.dish;

    // 导航到菜品详情页
    wx.navigateTo({
      url: `/src/pages/dish-detail/dish-detail?id=${dish.id}`
    });
  },
  
  // 添加到购物车
  onAddToCart: function(e) {
    const dish = e.detail.dish;

    // 获取购物车
    const app = getApp();
    const cart = app.globalData.cart || [];

    // 检查菜品是否已在购物车中
    const existingItem = cart.find(item => item.id === dish.id);

    if (existingItem) {
      // 如果已存在，增加数量
      existingItem.quantity += 1;
    } else {
      // 如果不存在，添加到购物车
      cart.push({
        ...dish,
        quantity: 1
      });
    }

    // 更新全局数据
    app.globalData.cart = cart;

    // 更新本地存储
    wx.setStorageSync('cart', cart);

    // 显示添加成功提示
    wx.showToast({
      title: '已添加到购物车',
      icon: 'success',
      duration: 1500
    });
  }
}) 